# -*- coding: utf-8 -*-
# @Time    : 2021/9/2 7:52 下午
# @Author  : zhongxin
# @Email   : 490336534@qq.com
# @File    : jsonoperator.py
import json
import os
from src.utils.constant import REPORT_PATH
from src.utils.logoperator import LogOperator

logger = LogOperator(__name__)

skip_steps = [
    "点击「同意」",
    "点击「允许」",
    "点击「确定」",
    "点击「稍后再说」",
    "点击「以后再说」",
    "点击「我知道了」",
    "点击「仅在使用中允许」",
    "点击「我知道啦」",
    "点击「始终允许」",
    "点击「仍然视频问诊」",
    "点击「知道了」",
    "点击「关闭」",
]


class JsonOperator:
    def __init__(self, path=None):
        self.path = path

    def read_json(self, path=None):
        if not path and self.path:
            path = self.path
        try:
            with open(path, "r", encoding='utf8') as f:
                json_data = json.load(f)
                return json_data
        except Exception as e:
            logger.error(f'读取json文件异常:{e}')
            return {}

    def get_steps(self, data, steps_data, num=None):
        if data:
            if not num:
                for index, i in enumerate(data):
                    self.get_steps(i, steps_data, index + 1)
            else:
                if all([s not in data["name"] for s in skip_steps]):
                    steps_data.append(f'{num}-{data["name"]}')
                if data.get("steps"):
                    n = 0
                    for j in data.get("steps"):
                        if all([s not in j.get("name") for s in skip_steps]):
                            n += 1
                            self.get_steps(j, steps_data, f"{num}.{n}")

    def get_allure_result(self, path=f'{REPORT_PATH}/allure_results'):
        """
        解析Allure报告中的result.json文件
        :param path: 存放allure运行json结果的文件夹
        :return:
        """
        result_list = [i for i in os.listdir(path) if '-result.json' in i]
        allure_results = []
        allure_dict = {}
        for i in result_list:
            json_data = self.read_json(os.path.join(path, i))
            full_name = json_data.get("fullName")
            labels = '_'.join([i.get('value', '') for i in json_data.get("labels") if
                               i.get('name', '') in ['feature', 'story']]) + "_" + json_data.get("name")
            parameters = json_data.get("parameters", '') and '_'.join([i.get('value', '') for i in
                                                                       json_data.get("parameters", '')])
            statusDetails = json_data.get('statusDetails', {})
            statusDetails1 = {
                "message": "",
                "trace": ""
            }
            if statusDetails:
                try:
                    message = statusDetails.get("message") and \
                              statusDetails.get("message").split("\n")[0] \
                                  .replace("selenium.common.exceptions.NoSuchElementException: Message:", "【异常】") \
                                  .replace("AssertionError:", "【断言】")
                    if message and "pytest_assume.plugin.FailedAssumption:" in message:
                        message = "【多重断言】" + ";".join(
                            [i for i in statusDetails.get("message").split("\n") if
                             i.startswith("AssertionError:")]).replace("AssertionError:", "")
                    statusDetails1["message"] = message or ""
                    statusDetails1["trace"] = statusDetails.get("trace", "")
                except Exception:
                    pass
            steps = []
            self.get_steps(json_data.get("steps"), steps)
            data = {
                "fullName": full_name,
                "status": json_data.get("status"),
                "labels": labels,
                "duration": json_data.get("stop", 0) - json_data.get("start", 0),
                "parameters": parameters,
                "statusDetails": statusDetails1,
                "steps": ";".join(steps)
            }
            if f'{full_name}_{parameters}' not in allure_dict:
                allure_dict[f'{full_name}_{parameters}'] = [data]
            else:
                allure_dict[f'{full_name}_{parameters}'].append(data)
        for v in allure_dict.values():
            message_list = []
            if len(v) == 1:
                allure_results.append(v[0])
            else:
                # 多次重跑存在通过的记录则标记为通过
                for v1 in v:
                    if 'pass' in v1.get("status"):
                        allure_results.append(v1)
                        break
                else:  # 多次重跑都失败
                    for v_i in v:
                        message_list.append(v_i['statusDetails']['message'].strip())
                    v[0]["statusDetails"]['message'] = ','.join(set(message_list))  # 错误信息合并
                    allure_results.append(v[0])
        return allure_results


if __name__ == '__main__':
    j = JsonOperator()
    allure_results = j.get_allure_result()
    print(len(allure_results))
    for i in allure_results:
        print(i)
